<template>
  <div>
    <el-card>
      <div slot="header" class="clearFix">
        <h2>商号和头像</h2>
      </div>

      <el-form ref="formData" :model="formData" label-width="200px">
        <el-form-item label="商号">
          <el-input class="input-width" v-model="formData.nick" placeholder="爱灵格"></el-input>
        </el-form-item>

        <el-form-item label="头像">
          <div>
            <img :src="downImgHost + formData.headImage" alt>
          </div>
          <div style="display: flex">
            <div class="info-item">
              <label class="btn btn-orange uploadBtn" for="uploads" style>选择图片</label>
              <input
                type="file"
                id="uploads"
                :value="imgFile"
                style="position:absolute; clip:rect(0 0 0 0);"
                accept="image/png, image/jpeg, image/gif, image/jpg"
                @change="uploadImg($event, 1)"
              >
              <el-button v-if="isUpload" size="small" class="add-style" @click="finish('blob')">保存图片</el-button>

              <div v-if="isUpload" class="line" style="margin-top: 85px;">
                <div class="cropper-content" style="margin-top:-60px;">
                  <div class="cropper">
                    <vueCropper
                      ref="cropper"
                      :img="option.img"
                      :outputSize="option.size"
                      :outputType="option.outputType"
                      :info="true"
                      :full="option.full"
                      :canMove="option.canMove"
                      :canMoveBox="option.canMoveBox"
                      :original="option.original"
                      :autoCrop="option.autoCrop"
                      :autoCropWidth="option.autoCropWidth"
                      :autoCropHeight="option.autoCropHeight"
                      :fixedBox="option.fixedBox"
                      @realTime="realTime"
                      @imgLoad="imgLoad"
                    ></vueCropper>
                  </div>
                  <div style="margin-left:20px;">
                    <div
                      class="show-preview"
                      :style="{'width': '150px', 'height':'155px',  'overflow': 'hidden', 'margin': '5px'}"
                    >
                      <div :style="previews.div" class="preview">
                        <img :src="previews.url" :style="previews.img">
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button
            :disabled="isUpload"
            @click="submitForm"
            class="widthBtn add-style"
            type="primary"
          >提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { VueCropper } from "vue-cropper";
import { setOrganizationInfo } from "api/profile.js";
import { uploadImageUrl, downImgHost } from "src/config/env";
import { getToken } from "src/util/auth";
import { mapState, mapMutations } from "vuex";
import axios from "axios";

export default {
  data() {
    return {
      headImg: "",
      //剪切图片上传
      crap: false,
      previews: {},
      option: {
        img: "",
        outputSize: 1, //剪切后的图片质量（0.1-1）
        full: false, //输出原图比例截图 props名full
        outputType: "png",
        canMove: true,
        original: false,
        canMoveBox: true,
        autoCrop: true,
        autoCropWidth: 150,
        autoCropHeight: 150,
        fixedBox: true
      },
      fileName: "", //本机文件地址
      downImg: "#",
      imgFile: "",
      uploadImgRelaPath: "", //上传后的图片的地址（不带服务器域名）

      formData: {
        nick: "", //昵称
        headImage: "" //头像
      },
      downImgHost: downImgHost,
      token: {},
      isUpload: false
    };
  },
  props: {
    enterpriceInfo: {
      type: Object,
      default() {
        return [];
      }
    }
  },
  watch: {
    enterpriceInfo: {
      handler: function(newVal, oldVal) {
        this.enterpriceInfo = newVal;
        this.dataInit();
      },
      deep: true
    }
  },
  computed: {
    ...mapState(["userInfo"])
  },
  components: {
    VueCropper
  },
  mounted() {
    this.dataInit();
    this.token.Authorization = getToken();
  },
  methods: {
    ...mapMutations(["GET_USERINFO", "RECORD_USERINFO"]),
    dataInit() {
      for (var i in this.formData) {
        for (var enterItem in this.enterpriceInfo) {
          if (i === enterItem) {
            this.formData[i] = this.enterpriceInfo[enterItem];
          }
        }
      }
    },
    //上传图片（点击上传按钮）
    finish(type) {
      // console.log("finish");
      let _this = this;
      let formData = new FormData();
      // 输出
      if (type === "blob") {
        this.$refs.cropper.getCropBlob(data => {
          let img = window.URL.createObjectURL(data);
          this.model = true;
          this.modelSrc = img;
          formData.append("file", data, this.fileName);

          axios({
            url: uploadImageUrl,
            method: "post",
            headers: { Authorization: getToken() },
            data: formData,
            timeout: 60 * 60 * 1000
          }).then(res => {
            if (res.data && res.data.status === 200) {
              this.formData.headImage = res.data && res.data.data;
              this.isUpload = false;
            } else {
              this.$message.error('error: '+ res.data.status +'，错误，请重试');
            }
          });
        });
      } else {
        this.$refs.cropper.getCropData(data => {
          this.model = true;
          this.modelSrc = data;
        });
      }
    },
    // 实时预览函数
    realTime(data) {
      // console.log("realTime");
      this.previews = data;
    },
    //下载图片
    down(type) {
      // console.log("down");
      var aLink = document.createElement("a");
      aLink.download = "author-img";
      if (type === "blob") {
        this.$refs.cropper.getCropBlob(data => {
          this.downImg = window.URL.createObjectURL(data);
          aLink.href = window.URL.createObjectURL(data);
          aLink.click();
        });
      } else {
        this.$refs.cropper.getCropData(data => {
          this.downImg = data;
          aLink.href = data;
          aLink.click();
        });
      }
    },
    //选择本地图片
    uploadImg(e, num) {
      // console.log("uploadImg");
      this.isUpload = true;
      var _this = this;
      //上传图片
      var file = e.target.files[0];
      _this.fileName = file.name;
      if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(e.target.value)) {
        alert("图片类型必须是.gif,jpeg,jpg,png,bmp中的一种");
        return false;
      }
      var reader = new FileReader();
      reader.onload = e => {
        let data;
        if (typeof e.target.result === "object") {
          // 把Array Buffer转化为blob 如果是base64不需要
          data = window.URL.createObjectURL(new Blob([e.target.result]));
        } else {
          data = e.target.result;
        }
        if (num === 1) {
          _this.option.img = data;
        } else if (num === 2) {
          _this.example2.img = data;
        }
      };
      // 转化为base64
      // reader.readAsDataURL(file)
      // 转化为blob
      reader.readAsArrayBuffer(file);
    },
    imgLoad(msg) {
      // console.log("imgLoad");
      // console.log(msg);
    },
    submitForm() {
      var data = {
        nick: this.formData.nick,
        headImage: this.formData.headImage
      };
      setOrganizationInfo(data).then(res => {
        this.GET_USERINFO();
        let userInfo = this.userInfo;
        this.RECORD_USERINFO(userInfo);
        this.$message.success("数据已上传！");
      });
    }
  }
};
</script>

<style lang="less">
.imgCropper {
  width: 200px;
  height: 200px;
}
.input-width {
  width: 400px;
}
.upload-width {
  width: 400px;
}

.widthBtn {
  width: 200px;
  margin: 20px 200px 0 0;
}

// ------------头像---------------
.uploadBtn {
  border: 1px solid #f1f1f1;
  padding: 9px 15px;
  background: #00bcd4;
  color: #fff;
  display: inline-block;
  text-align: center;
  line-height: 16px;
  border-radius: 4px;
}

.info {
  width: 720px;
  margin: 0 auto;
  .oper-dv {
    height: 20px;
    text-align: right;
    margin-right: 100px;
    a {
      font-weight: 500;
      &:last-child {
        margin-left: 30px;
      }
    }
  }
  .info-item {
    margin-top: 15px;
    label {
      display: inline-block;
      width: 100px;
      text-align: right;
    }
    .sel-img-dv {
      position: relative;
      .sel-file {
        position: absolute;
        width: 90px;
        height: 30px;
        opacity: 0;
        cursor: pointer;
        z-index: 2;
      }
      .sel-btn {
        position: absolute;
        cursor: pointer;
        z-index: 1;
      }
    }
  }
}

.cropper-content {
  display: flex;
  display: -webkit-flex;
  justify-content: flex-end;
  -webkit-justify-content: flex-end;
  .cropper {
    width: 260px;
    height: 260px;
  }
  .show-preview {
    flex: 1;
    -webkit-flex: 1;
    display: flex;
    display: -webkit-flex;
    justify-content: center;
    -webkit-justify-content: center;
    .preview {
      overflow: hidden;
      // border-radius: 50%;
      border: 1px solid #cccccc;
      background: #cccccc;
      margin-left: 40px;
    }
  }
}
.cropper-content .show-preview .preview {
  margin-left: 0;
}

</style>